<template>
  <div class="home" @scroll="scroll_nav" ref="homeTop">
    <!-- 导航头 -->
    <div :class="isNavClass ?  navClass : ['nav']">
      <Top_nva :enter="enter" :isUserText="isUserText"></Top_nva>
    </div>
    <!-- 轮播图 -->
    <div class="banner">
      <div class="block">
        <el-carousel height="700px" :interval="5000">
          <el-carousel-item v-for="item in imgArr" :key="item">
            <img :src="item" alt="">
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
    <!-- 易物商城上线啦！ -->
    <div class="gridClass">
      <div class="gridClass-text">
        <span>
          易物商城上线啦
        </span>
        <span>
          全场促销5.5折,享受运费险! 并且可以得到不一样的购物体验
        </span>
        <span>
          慢就赔 - 贵就赔 - 全面保
        </span>
      </div>
      <!-- 推荐商品 -->
      <div class="gridClass-item">
        <Home_GridClass v-for="item in recommendSideber" :key="item.productId">
          <template slot="img">
            <img :src="'http://43.138.33.247/' + item.productImg.url" alt="" srcset="">
          </template>
          <template slot="text">
            {{item.productName}}
          </template>
        </Home_GridClass>
      </div>
    </div>
    <!-- item商品 -->
    <div class="listClass">
      <div class="list_" v-for="(item,index)  in sideber" :key="index" ref="list_">
        <span>{{item.name}}</span>
        <div class="list_items">
          <div class="list_item" v-for="items in commodity[index]" :key="items.categoryId" @click="commodityItemClick(items.categoryId)">
            {{items.categoryName}}
            {{items.categoryId}}
          </div>
        </div>

      </div>

    </div>

    <!-- 侧边导航栏 :list_top="list_offsetTop" -->
    <Home_sideber :style="homeSideber" :sideber="sideber" :listTop="listArr"></Home_sideber>

  </div>
</template>

<script>
// 导入三级数据
import { codeToText, regionData } from 'element-china-area-data'

import { getThreeLevelList, getRecommendSideber, postAddress, getUserAddress } from '../config/api'

import Top_nva from '../components/Top-nav'
import Home_sideber from '../components/Home-sideber'
import Home_GridClass from '../components/Home-GridClass'
export default {
  data() {
    return {
      throttle: 0, // 为监听滚动事件内的top节流(避免重复设置) 1为大于 0为小于
      isNavClass: false,
      navClass: ['nav_top', 'nav'],
      // 控制个人信息的显示
      isUserText: true,
      token: this.$token(),
      imgArr: [require('../assets/img/原神拔笋妹妹版.jpg'), require('../assets/img/原神拔笋哥哥版.jpg'), require('../assets/img/6花.jpg'), require('../assets/img/神里甘雨.jpg')],
      // 控制侧边栏的位置
      homeSideber: { right: '-100px' },
      // 存储侧边栏的状态和商品信息   给些默认数据 防止刚加载页面时 滚动屏幕导致监听滚轮事件内的报错 和 计算属性内对ref的使用length报错
      sideber: [
        { name: '麻辣香锅', isSideber: false },
        { name: '小龙虾', isSideber: false },
        { name: '薯片', isSideber: false },
        { name: '麻辣香锅', isSideber: false },
        { name: '小龙虾', isSideber: false },
        { name: '薯片', isSideber: false }
      ],
      // 防抖
      timeout: null,
      // 配合计算属性使用
      listArr: [],
      // 推荐商品
      recommendSideber: [],
      // 存储商品item
      commodity: []
    }
  },
  components: {
    Top_nva,
    Home_sideber,
    Home_GridClass
  },
  methods: {
    // 子组件的回车事件
    enter(value) {
      console.log(value)
    },
    // 监听滚动条
    scroll_nav(event) {
      // 距离文档头部的距离
      let scrollTop = this.$refs.homeTop.scrollTop
      // 判断item的距离
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        let is = false
        for (let i = this.list_offsetTop.length; i > 0; i--) {
          if (this.sideber[i - 1] == undefined) return
          this.sideber[i - 1].isSideber = false

          if (scrollTop + 150 > this.list_offsetTop[i - 1]) {
            // 从后遍历 进入第一个大于之后只保留当前的true其他的继续改成false
            this.sideber[i - 1].isSideber = true
            if (is) {
              this.sideber[i - 1].isSideber = false
            }
            is = true
          }
        }
      }, 300)
      // top栏
      if (scrollTop > 780) {
        if (this.throttle == 1) return
        // console.log('大于')
        this.throttle = 1
        this.isNavClass = true
        this.isUserText = false
        this.homeSideber.right = '50px'
      } else {
        if (this.throttle == 0) return
        // console.log('小于')
        this.throttle = 0
        this.isNavClass = false
        this.isUserText = true
        this.homeSideber.right = '-100px'
      }
    },
    // 商品点击
    commodityItemClick(id) {
      // console.log(id)
      this.$router.push({
        path: '/commodity',
        query: {
          commodityItemId: id
        }
      })
    },
    // 三级区域选择变化
    handleChange(value) {
      for (let i = 0; i < this.selectedOptions.length; i++) {
        this.loc[i] = codeToText[this.selectedOptions[i]]
      }
      // 添加到请求对象中
      this.addressObj.province = this.loc[0] // 省
      this.addressObj.city = this.loc[1] // 市
      this.addressObj.area = this.loc[2] // 县
    },
    // 确定 发起请求
    address_post() {
      this.$isExistUser()
      if (!this.addressObj.receiverName) return this.$message.error('请填写姓名')
      if (!this.addressObj.receiverMobile) return this.$message.error('请填写手机号')
      if (!this.loc[0]) return this.$message.error('请选择区域')

      // this.addressObj.userId = window.localStorage.getItem('userId') // 用户id

      postAddress(this.token, this.addressObj)
        .then(result => {
          if (result.status == 200) {
            if (result.data.code == 200) {
              this.dialogFormVisible = false
              this.getAddress()

              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
            }
          }
        })
        .catch(err => {
          // console.log(err)
          this.$message.error('添加失败')
        })
    }
  },
  computed: {
    // 存储每一项商品列表距离文档top值
    list_offsetTop() {
      this.listArr = []
      for (let i = 0; i < this.$refs.list_.length; i++) {
        // console.log(this.$refs.list_[i].offsetTop)
        this.listArr.push(this.$refs.list_[i].offsetTop)
      }
      return this.listArr
    }
  },
  created() {
    // 请求三级列表
    getThreeLevelList()
      .then(result => {
        // console.log(result.data.data)
        if (result.status == 200) {
          let sidebers = []
          for (let i = 0; i < result.data.data.length; i++) {
            let obj = {}
            obj.name = result.data.data[i].categoryName
            obj.isSideber = false
            sidebers.push(obj)
            for (let t = 0; t < result.data.data[i].categoryVOList.length; t++) {
              this.commodity.push(result.data.data[i].categoryVOList[t].categoryVOList)
            }
          }
          this.sideber = sidebers
        }
      })
      .catch(err => {
        if (err.code == 'ERR_BAD_REQUEST') {
          console.log(err)
        }
      }),
      // 推荐商品
      getRecommendSideber()
        .then(result => {
          // console.log(result)
          if (result.status == 200) {
            if (result.data.code == 200) {
              this.recommendSideber = result.data.data
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
  },
  mounted() {}
  // beforeRouteEnter: (to, from, next) => {
  //   if (window.localStorage.getItem('userId') == null) {
  //     next(vm => {
  //       vm.$router.push({
  //         path: '/login',
  //         query: {
  //           top_nav: true
  //         }
  //       })
  //     })
  //   } else {
  //     next()
  //   }
  // }
}
</script>

<style lang="less" scoped>
::-webkit-scrollbar {
  display: none; /* Chrome Safari 隐藏导航条 且可以滚动 */
}
* {
  //  隐藏导航条 且可以滚动
  -ms-overflow-style: none; /* IE 10+ */
  scrollbar-width: none; /* Firefox */
}
.home {
  position: relative;
  width: 100%;
  overflow: scroll;
  height: 100vh;
  // transition: 1s;
  .nav_top {
    // 防止下方grid-item的hover效果压到导航条
    z-index: 99;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background-color: @nav_back;
  }
  // .nav {
  //   // transition: 1s;
  // }
  // 轮播图
  .banner {
    // height: calc(100vh - 60px);
    .block {
      height: 100%;
    }
    img {
      width: 100%;
      height: 100%;
    }
  }
  // item分类
  .gridClass {
    display: flex;
    width: 1200px;
    height: 140px;
    margin: 30px auto;
    // box-shadow: 0.1em 0em 0.5em rgb(150, 150, 147);
    box-shadow: 0em 0em 1em 5px #969693;
    background-color: @html_back;
    color: @html_color;
    border-radius: 10px;
    .gridClass-text {
      padding: 20px 0;
      margin: 0 30px;
      width: 200px;
      span {
        display: block;
        text-align: center;
      }
      & span:nth-child(1) {
        font-size: 20px;
        font-weight: bold;
      }
      & span:nth-child(2) {
        font-size: 14px;
        margin-top: 10px;
      }
      & span:nth-child(3) {
        font-size: 16px;
        margin-top: 10px;
      }
    }
    .gridClass-item {
      // 5个item
      width: 150px * 5;
      display: flex;
      justify-content: space-evenly;
      align-items: center;
    }
  }
  .listClass {
    width: 1200px;
    margin: 0px auto;
    .list_ {
      color: @html_color;
      font-size: 18px;
      .list_items {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        .list_item {
          width: 200px;
          height: 250px;
          margin: 10px;
          border: 1px solid #969693;
          cursor: pointer;

          text-align: center;
        }
        .list_item:hover {
          transform: translateY(-3px);
        }
      }
    }
  }
}
</style>